import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { withRouter, connect } from 'umi';
import {
  Button,
  Table,
  Modal,
  Form,
  Input,
  Select,
  notification,
  Row,
  Col,
} from 'antd';
import {
  deviceUpdate,
  deviceAdd,
  getSystemInfoList, // 查询 系统资讯
  getEquipmentList, // 查询 设备资讯
} from './setServers';
import {
  listAllBySiteID, // 根据Site 查询
  getModelList, // 根据感测器类型 中含有厂牌
  listAllByBuildingID, // 根据建物资讯
} from './setServers';
import styles from '@/assets/setting/BuildSet.less';

const { Option } = Select;
/**
 * 动态生成下拉框
 * @param list 全部的列表
 * @param valN key 值
 * @param name 显示的名称
 * @returns
 */
const selectOption = (list: any[], valN: string, name: string) => {
  return list.map((item: any) => (
    <Option key={item[valN]} value={item[valN]}>
      {item[name]}
    </Option>
  ));
};

/* 感测器 添加 */
const SensorModal = (props: any) => {
  const [FormModal] = Form.useForm();
  const { modalVisible, typeBuildData, meterModelData, stateTypeListAll } =
    props;
  const { modalOnCancel, upAddModal, addModalData } = props;

  const [areaIdList, setAreaIdList] = useState([]);

  return (
    <Modal
      title={'新增'}
      forceRender={false}
      visible={modalVisible}
      maskClosable={false}
      onOk={() => {
        FormModal.validateFields().then((val: any) => {
          // console.log('上传添加的数据', val);
          if (val['metermodel'] === '无') {
            val['metermodel'] = '';
          }
          // console.log(addModalData, addModalData['siteId']);
          const paramsUp = {
            devicetype: addModalData['deviceType'],
            siteid: addModalData['siteId'],
            ...val,
          };
          if (upAddModal(paramsUp)) {
            FormModal.resetFields();
          }
        });
      }}
      onCancel={modalOnCancel}
    >
      <Form
        form={FormModal}
        name="FormModal"
        labelCol={{ span: 5 }}
        autoComplete="off"
        initialValues={{
          cname: '',
          buildingid: '',
          areaid: '',
          readfreq: '',
          status: '',
          metermodel: '',
        }}
      >
        <Form.Item name="cname" label="感测器名称">
          <Input />
        </Form.Item>
        <Form.Item name="buildingid" label="建物名称">
          <Select
            onChange={(val: string) => {
              console.log('选择 sit 后的数据', val);
              listAllByBuildingID({ buildingId: val }).then((res) => {
                console.log('获取 区域名称数据', res);
                if (res['data'].length) {
                  setAreaIdList(res['data']);
                }
              });
            }}
          >
            {typeBuildData.length && selectOption(typeBuildData, 'ID', 'NAME')}
          </Select>
        </Form.Item>
        <Form.Item name="areaid" label="区域名称">
          <Select>
            {areaIdList.length && selectOption(areaIdList, 'ID', 'NAME')}
          </Select>
        </Form.Item>
        <Form.Item name="readfreq" label="读取频率（秒）">
          <Select>
            <Option value="10">10</Option>
            <Option value="300">300</Option>
          </Select>
        </Form.Item>
        <Form.Item name="status" label="感测器状态">
          <Select>
            {stateTypeListAll.length &&
              selectOption(stateTypeListAll, 'Code', 'Remark')}
          </Select>
        </Form.Item>
        <Form.Item name="metermodel" label="感测器厂牌">
          <Select>
            {meterModelData.length &&
              selectOption([{ NAME: '无' }, ...meterModelData], 'NAME', 'NAME')}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};
/* 感测器 编辑 */
const EditModal = (props: any) => {
  const [editForm] = Form.useForm();

  const {
    modalVisible,
    editModalData,
    deviceTypeListAll,
    facListAll,
    stateTypeListAll,
  } = props;
  const { editModalOnOk, editModalOnCancel } = props;

  console.log('传递过来的数据！！！', props);

  // 厂牌
  const [facMID, setFacMID] = useState([]);
  // 建物
  const [buildingList, setBuildingList] = useState([]);
  // 区域
  const [areaList, setAreaList] = useState([]);
  // 系统
  const [systemList, setSystemList] = useState([]);
  // 设备
  const [equipmentList, setEquipmentList] = useState([]);
  // 频率
  const frequencyData = [
    { time: '10', value: '10' },
    { time: '300', value: '300' },
  ];

  // 查询 厂牌
  const getFactoryName = (params: { dType: string }) => {
    getModelList(params).then((res) => {
      console.log('查询全部厂牌', res);
      res && setFacMID(res['data']);
    });
  };
  // 查询 建物
  const getBuildingName = (params: { siteId: string }) => {
    listAllBySiteID(params).then((res) => {
      setBuildingList(res['data']);
    });
  };
  // 查询 区域
  const getAreaName = (params: { buildingId: string }) => {
    listAllByBuildingID(params).then((res) => {
      setAreaList(res['data']);
    });
  };
  // 查询 系统
  const getSystemName = (params: { buildingId: string; sId: string }) => {
    getSystemInfoList(params).then((res) => {
      res && setSystemList(res['data']);
    });
  };
  // 查询 设备
  const getEquipmenName = (params: { sId: string }) => {
    getEquipmentList(params).then((res) => {
      res && setEquipmentList(res['data']);
    });
  };

  useEffect(() => {
    // 获取 厂牌
    getFactoryName({ dType: editModalData['DEVICETYPE'] });
    // 获取 建物资讯
    getBuildingName({ siteId: editModalData['SITEID'] });
    // 获取 区域资讯
    getAreaName({ buildingId: editModalData['BUILDINGID'] });
    // 获取 系统资讯 BUILDINGNAME
    getSystemName({
      buildingId: editModalData['BUILDINGID'],
      sId: editModalData['SITEID'],
    });
    // 获取 设备资讯
  }, [modalVisible]);

  return (
    <Modal
      title={'ID: ' + editModalData['ID'] || '编辑'}
      width={800}
      maskClosable={false}
      forceRender={false}
      visible={modalVisible}
      onOk={() => {
        editForm.validateFields().then((res) => {
          console.log('获取 Form 全部的数据', res);
          const params = {
            id: editModalData['ID'],
            cname: res['CNAME'],
            buildingname: res['BUILDINGNAME'],
            devicetype: res['DEVICETYPE'],
            metermodel: res['METERMODEL'],
            buildingid: res['BUILDINGID'],
            areaname: res['AREANAME'],
            systemmid: res['SYSTEMID'],
            equipid: res['EQUIPID'],
            readfreq: res['READFREQ'],
            status: res['STATUS'],
            remark: res['REMARK'],
          };
          deviceUpdate(params)
            .then((res) => {
              console.log('是否上传成功！！！', res);
              if (res.code >= 0) {
                notification.success({
                  message: '更新结果！',
                  description: res.message || '更新成功！',
                });
                editModalOnOk();
              } else {
                notification.error({
                  message: '更新结果',
                  description: res.message || '更新失败！',
                });
              }
            })
            .catch((rej) => {
              notification.error({
                message: '更新结果',
                description: rej.message || '更新失败！',
              });
            });
        });
      }}
      onCancel={editModalOnCancel}
    >
      <Form
        form={editForm}
        name="editForm"
        labelCol={{ span: 5 }}
        autoComplete="off"
        initialValues={{
          CNAME: '',
          ...editModalData,
        }}
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="感测器名称" name="CNAME">
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="Site" name="BUILDINGNAME">
              <Input disabled />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="感测器类型" name="DEVICETYPE">
              <Select
                onChange={(val: string) => {
                  getFactoryName({ dType: val });
                  console.log('感测器类型选择 改变厂牌', val);
                }}
              >
                {selectOption(deviceTypeListAll, 'id', 'typename')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="感测器厂牌" name="METERMODEL">
              <Select>{selectOption(facMID, 'NAME', 'NAME')}</Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="建物资讯" name="BUILDINGID">
              <Select
                onChange={(val: string) => {
                  console.log(val, editModalData['SITEID']);
                  // 改变 区域资讯 系统资讯 数据
                  getAreaName({ buildingId: val });
                  getSystemName({
                    buildingId: val,
                    sId: editModalData['SITEID'],
                  });
                }}
              >
                {selectOption(buildingList, 'ID', 'NAME')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="区域资讯" name="AREANAME">
              <Select>{selectOption(areaList, 'ID', 'NAME')}</Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="系统资讯" name="SYSTEMID">
              <Select
                onChange={(val: string) => {
                  console.log('系统资讯 val', val);
                  getEquipmenName({ sId: val });
                }}
              >
                {selectOption(systemList, 'ID', 'NAME')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="设备资讯" name="EQUIPID">
              <Select>{selectOption(equipmentList, 'ID', 'NAME')}</Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="读取频率（秒）" name="READFREQ">
              <Select>{selectOption(frequencyData, 'value', 'time')}</Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="感测器状态" name="STATUS">
              <Select>
                {selectOption(stateTypeListAll, 'Code', 'Remark')}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label="柱位" name="">
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="备注" name="REMARK">
              <Input />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

/* 感测器资讯设定 表格 */
const SensorSetTable = (props: any) => {
  // console.log('感测器资讯设定 表格', props);
  const { dvaData, history } = props;
  const { getByCondition, addModalData } = props;
  const { typeBuildData, meterModelData, stateTypeListAll } = props;
  const { sensorTabD } = props;

  // console.log(dvaData, 'dvaData 数据！！！');
  const [modalVisible, setModalVisible] = useState(false);
  // 表格数据编辑
  const [editModalVist, setEditModalVist] = useState(false);
  type EditModalData = { [key: string]: any };
  const [editModalData, setEditModalData] = useState<EditModalData>({});

  /* 返回感测器状态 */
  const rStatus = (str: string) => {
    if (!str) return str;
    for (const item of stateTypeListAll) {
      if (item['Code'] === str) {
        return item['Remark'];
      }
    }
  };
  /* 关闭 编辑 添加 Mobal */
  const modalOnCancel = () => {
    setModalVisible(false);
  };
  /* 更新，新增 数据 */
  const upAddModal = (val: any) => {
    let success = true;
    deviceAdd(val)
      .then((res) => {
        console.log('数据添加成功', res);
        notification.success({
          message: '添加结果！',
          description: res.message || '添加成功！',
        });
        setModalVisible(false);
        getByCondition();
      })
      .catch((rej: any) => {
        success = false;
        notification.error({
          message: '添加结果！',
          description: rej.message || '添加失败！',
        });
      });
    return success;
  };
  /* 关闭 编辑 Mobal */
  const editModalOnCancel = () => {
    setEditModalVist(false);
  };
  /* 确认 上传更新的数据 */
  const editModalOnOk = () => {
    setEditModalVist(false);
    getByCondition();
  };
  /* 表格数据编辑 */
  const sensorModalEdit = useMemo(() => {
    return (
      <EditModal
        modalVisible={editModalVist}
        editModalData={editModalData}
        editModalOnOk={editModalOnOk}
        editModalOnCancel={editModalOnCancel}
        deviceTypeListAll={dvaData['deviceTypeListAll']}
        facListAll={dvaData['facListAll']}
        stateTypeListAll={dvaData['stateTypeListAll']}
      />
    );
  }, [editModalVist]);

  const tableThead = [
    { title: 'ID', dataIndex: 'ID', key: 'ID' },
    { title: '感测器名称', dataIndex: 'CNAME', key: 'CNAME' },
    { title: '建物名称', dataIndex: 'BUILDINGNAME', key: 'BUILDINGNAME' },
    { title: '区域名称', dataIndex: 'AREANAME', key: 'AREANAME' },
    { title: '读取频率(秒)', dataIndex: 'READFREQ', key: 'READFREQ' },
    {
      title: '感测器状态',
      dataIndex: 'STATUS',
      key: 'STATUS',
      render: (text: string) => rStatus(text),
    },
    { title: '感测器厂牌', dataIndex: 'METERMODEL', key: 'METERMODEL' },
    {
      title: '上下限设定',
      render: (record: any) => (
        <Button
          type="link"
          onClick={() => {
            console.log('上下限！！！', record);
            history.push(`/SensorLimitMtn/${record['ID']}`, record);
            // setUpLowerModalVist(true)
            // setUpLowerModalData(record)
          }}
        >
          上下限
        </Button>
      ),
    },
    {
      title: '智能调控设定',
      render: (record: any) => (
        <Button
          type="link"
          onClick={() => {
            // '/TagMapping/:deviceType/:id'
            // if( record['DEVICETYPE'] && record['ID'] ) {}
            history.push(
              `/TagMapping/${record['DEVICETYPE']}/${record['ID']}`,
              record,
            );
          }}
        >
          智能调控
        </Button>
      ),
    },
    { title: 'Config设定', render: () => <Button type="link">config</Button> },
    {
      title: '处理',
      render: (record: any) => (
        <Button
          type="primary"
          size="small"
          onClick={() => {
            console.log('编辑！！！', record);
            setEditModalVist(true);
            setEditModalData(record);
          }}
        >
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div>
      {sensorTabD && (
        <>
          <Button type="primary" ghost onClick={() => setModalVisible(true)}>
            添加
          </Button>
          <Table
            rowKey={(record: any): string => record['ID'] + record['MID']}
            className={styles['sensorSetTab']}
            size="middle"
            columns={tableThead}
            dataSource={sensorTabD}
            pagination={false}
          />
        </>
      )}
      {/* 添加 */}
      <SensorModal
        modalVisible={modalVisible}
        modalOnCancel={modalOnCancel}
        typeBuildData={typeBuildData}
        meterModelData={meterModelData}
        stateTypeListAll={stateTypeListAll}
        addModalData={addModalData}
        upAddModal={upAddModal}
      />
      {/* 编辑 */}
      {editModalVist && sensorModalEdit}
    </div>
  );
};

/* 挂载 到仓库中 */
const sensorToProps = (state: any) => ({
  dvaData: state.setting,
});
export default connect(sensorToProps)(withRouter(SensorSetTable));
